package ws

/**
import (
	"svr/src/logs"
	"svr/src/msg"
	"svr/src/xutil"
	"sync"
	"time"

	"google.golang.org/protobuf/proto"
)

var mapWaitTasks *xutil.Map
var delKeys []int64
var lock sync.RWMutex

type WaitTask struct {
	Call      func(ma proto.Message, err *msg.Error)
	MsgA      proto.Message
	Timestamp time.Time
}

func addTaskWait(key int64, ma proto.Message, call func(ma proto.Message, err *msg.Error)) {
	wt := &WaitTask{
		Call:      call,
		MsgA:      ma,
		Timestamp: time.Now(),
	}
	if mapWaitTasks == nil {
		lock.Lock()
		if mapWaitTasks == nil {
			mapWaitTasks = xutil.CreateMap()
			AddUpdateTask("task wait", 10*time.Second, updateTask)
		}
		lock.Unlock()
	}
	mapWaitTasks.Set(key, wt)
}

func checkTaskWait(mi *MsgInfo) bool {
	if mapWaitTasks == nil {
		return false
	}
	k := mi.Conf.MsgCode
	v := mapWaitTasks.Get(k)
	if v != nil {
		go func() {
			wt := v.(*WaitTask)
			if mi.Conf.Err != nil {
				wt.Call(nil, mi.Conf.Err)
			} else {
				err := proto.Unmarshal(mi.Data, wt.MsgA)
				if err != nil {
					logs.Errorf("msg :%+v check error!!!", wt.MsgA)
					wt.Call(nil, CreateMsgError(msg.ErrCode_Err_Unmarshal, mi.Conf.Name+" Unmarshal error!!"))
				} else {
					wt.Call(wt.MsgA, nil)
				}
			}
			mapWaitTasks.Delete(k)
		}()
		return true
	}
	return false
}

func updateTask(now time.Time) { //这里主要是清理超过30秒没回的消息
	// for {
	limitTime := now.Add(-time.Second * 30)
	mapWaitTasks.Walk(func(k interface{}, v interface{}) {
		key := k.(int64)
		wt := v.(*WaitTask)
		if wt.Timestamp.Before(limitTime) {
			delKeys = append(delKeys, key)
		}
	})
	if delKeys != nil {
		for _, k := range delKeys {
			v := mapWaitTasks.Get(k)
			if v != nil {
				wt := v.(*WaitTask)
				wt.Call(nil, CreateMsgError(msg.ErrCode_Err_Timeout, GetMessageName(wt.MsgA)+" wait timeout!"))
				mapWaitTasks.Delete(k)
			}
		}
	}
	// 	time.Sleep(time.Second * 10)
	// }
}
func CreateMsgError(code msg.ErrCode, result string) *msg.Error {
	return &msg.Error{Code: code, Result: result}
}
/**/
